package com.taglab.chic.taglib.analytics;

import javax.servlet.jsp.tagext.TagSupport;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;

/**
 * Override elements of the analytics tag, prior to GoogleAnalyticsTag declaration (which should always be last or near
 * last). Useful for overriding analytics behaviour from within templated JSP pages.
 */
public class GoogleAnalyticsOverridesTag extends TagSupport {

  private static final long serialVersionUID = 1863037864811229996L;

//  private final static Logger logger = LoggerFactory.getLogger(GoogleAnalyticsOverridesTag.class);

  public static final String DISABLED_VAR = "googleAnalyticsDisabled";
  public static final String TRACKERNAME_VAR = "googleAnalyticsTrackerName";
  public static final String TRACKERCODE_VAR = "googleAnalyticsTrackerCode";
  public static final String URLOVERRIDE_VAR = "googleAnalyticsTrackingUrl";
  public static final String TRANSACTION_VAR = "googleAnalyticsTransaction";
  public static final String EVENT_VAR = "googleAnalyticsEvent";

  private Boolean disabled;
  private String trackerName;
  private String trackerCode;
  private String urlOverride;
  private Transaction transaction;
  private Event event;

  public void setDisabled(Boolean disabled) {
    this.disabled = disabled;
  }

  public void setTrackerName(String trackerName) {
    this.trackerName = trackerName.trim();
  }

  public void setTrackerCode(String trackerCode) {
    this.trackerCode = trackerCode.trim();
  }

  public void setUrlOverride(String urlOverride) {
    this.urlOverride = urlOverride.trim();
  }

  public void setTransaction(Transaction transaction) {
    this.transaction = transaction;
  }

  public void setEvent(Event event) {
    this.event = event;
  }

  @Override
  public int doStartTag() throws JspException {
    // Put defined variables into page context
    if ( disabled != null ) setRequestAttribute(DISABLED_VAR, disabled);
    if ( trackerName != null ) setRequestAttribute(TRACKERNAME_VAR, trackerName);
    if ( trackerCode != null ) setRequestAttribute(TRACKERCODE_VAR, trackerCode);
    if ( urlOverride != null ) setRequestAttribute(URLOVERRIDE_VAR, urlOverride);
    if ( transaction != null ) setRequestAttribute(TRANSACTION_VAR, transaction);
    if ( event != null ) setRequestAttribute(EVENT_VAR, event);

    return SKIP_BODY;
  }

  private void setRequestAttribute(String var, Object value) {
    pageContext.setAttribute(var, value, PageContext.REQUEST_SCOPE);
  }

}
